/*
 * Copyright The OpenTelemetry Authors
 * SPDX-License-Identifier: Apache-2.0
 */

package com.xiashitech.agent.instrumentation.netty.netty_v4_1.inst;

import io.netty.channel.ChannelPipeline;
import io.opentelemetry.javaagent.bootstrap.CallDepth;
import io.opentelemetry.javaagent.extension.instrumentation.TypeInstrumentation;
import io.opentelemetry.javaagent.extension.instrumentation.TypeTransformer;
import net.bytebuddy.asm.Advice;
import net.bytebuddy.description.type.TypeDescription;
import net.bytebuddy.matcher.ElementMatcher;
import static net.bytebuddy.matcher.ElementMatchers.*;

public class AbstractChannelHandlerContextInstrumentation implements TypeInstrumentation {
   // private static final Logger logger = Logger.getLogger("AbstractChannelHandlerContextInstrumentation");
    @Override
    public ElementMatcher<TypeDescription> typeMatcher() {
        // return implementsInterface(named("com.alibaba.nacos.shaded.io.grpc.netty.shaded.io.netty.channel.ChannelOutboundInvoker"));
        return named("io.netty.channel.DefaultChannelPipeline");
    }


    @Override
    public void transform(TypeTransformer transformer) {
        System.out.println("###aaa1");
        transformer.applyAdviceToMethod(
                isMethod()
                        .and(named("writeAndFlush"))
                        .and(takesArgument(0, named("java.lang.Object")))
                        .and(takesArguments(1))
                        .and(isPublic()).and(isFinal()),
                AbstractChannelHandlerContextInstrumentation.class.getName() + "$WriteAndFlushAdvice");

            System.out.println("###aaa2");

    }



    @SuppressWarnings("unused")
    public static class WriteAndFlushAdvice {
        @Advice.OnMethodEnter
        public static void onEnter(
            @Advice.Argument(0) Object msg,
            @Advice.This ChannelPipeline pipeline,
            @Advice.Local("otelCallDepth") CallDepth callDepth
        ) {
           // msg ="13552603292";
        System.out.println("###bbb1");
/*
            ByteBuf byteBuf = (ByteBuf)msg;
            byte[] bytes = new byte[byteBuf.readableBytes()];
            byteBuf.readBytes(bytes);
            String message = new String(bytes);*/


          //  System.out.println(ctx.fireChannelRead(msg).toString());

            System.out.println("###bbb2");
        }

        @Advice.OnMethodExit(onThrowable = Throwable.class, suppress = Throwable.class)
        public static void onExit() {
            System.out.println("###ccc");
        }
    }
}
